<script setup lang="ts">
  import type { InputOnBlurEvent } from "@uni-helper/uni-app-types/index"
  import { ref } from "vue"
  import type { PatientParams } from "@/types/patient"
  import { addPatientApi, patientDetailApi, updatePatientApi } from "@/apis/patient"

  const prop = defineProps<{ id?: string }>()
  // 1. 表单数据
  const formData = ref({
    name: "",
    idCard: "",
    gender: 1,
    defaultFlag: 1,
  })
  // 2. 表单验证规则
  const formRules = {
    name: {
      rules: [
        { required: true, errorMessage: "请填写患者姓名" },
        {
          pattern: /^[\u4e00-\u9fa5]{2,5}$/,
          errorMessage: "患者姓名为2-5位中文",
        },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: "请输入身份证号" },
        {
          pattern:
            /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
          errorMessage: "身份证号格式不正确",
        },
      ],
    },
    gender: {
      rules: [
        {
          required: true,
          errorMessage: "请选择性别",
        },
        {
          validateFunction: function (rule, value, data, callback) {
            if (parseInt(formData.value.idCard.at(-2)!) % 2 === 1 && formData.value.gender !== 1) {
              callback("只能男生 不能是女生")
            } else if (
              parseInt(formData.value.idCard.at(-2)!) % 2 === 0 &&
              formData.value.gender !== 0
            ) {
              callback("只能女生 不能是男生")
            }
            return true
          },
        },
      ],
    },
  }
  // 3. ref 关联表单组件
  const form = ref<UniHelper.UniFormsInstance>()
  const nameRef = ref<UniHelper.UniFormsItemInstance>()
  const idCardRef = ref<UniHelper.UniFormsItemInstance>()
  const genderRef = ref<UniHelper.UniFormsItemInstance>()

  // 切换默认就诊人
  const onDefaultChange = () => {
    if (formData.value.defaultFlag === 1) {
      formData.value.defaultFlag = 0
    } else {
      formData.value.defaultFlag = 1
    }
  }

  const aaaa = (e) => {
    formData.value.gender = e.detail.value
    genderRef.value?.onFieldChange?.(formData.value.gender)
  }

  // 表单提交
  const onSubmit = async () => {
    try {
      // 判断是否存在id 表示新增还是编辑
      if (prop.id) {
        // 编辑
        await form.value?.validate?.()
        // 后端要的参数，一定要带上id
        const params: PatientParams = formData.value
        params.id = prop.id
        await updatePatientApi(params)
        uni.showToast({ title: "更新成功" })
      } else {
        await form.value?.validate?.()
        const params: PatientParams = formData.value
        await addPatientApi(params)
        // ----
        uni.showToast({ title: "新增成功" })
      }
      uni.navigateBack()
    } catch (error) {
      console.log("error", error)
    }
  }

  // 获取详情数据
  const getDetailById = async () => {
    if (prop.id) {
      // 修改标题
      uni.setNavigationBarTitle({ title: "更新患者" })
      // 发送请求。。。
      const res = await patientDetailApi(prop.id)
      // console.log(res)
      // 数据回填
      formData.value.name = res.name
      formData.value.idCard = res.idCard
      formData.value.gender = res.gender!
      formData.value.defaultFlag = res.defaultFlag
    } else {
      uni.setNavigationBarTitle({ title: "新增患者" })
    }
  }
  getDetailById()
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name" ref="nameRef">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
            @blur="(e:InputOnBlurEvent)=>nameRef?.onFieldChange?.(e.detail.value)"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard" ref="idCardRef">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="formData.idCard"
            @blur="(e:InputOnBlurEvent)=>idCardRef?.onFieldChange?.(e.detail.value)"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender" ref="genderRef">
          <uni-data-checkbox
            :value="formData.gender"
            @change="aaaa"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              :checked="formData.defaultFlag === 1"
              @change="onDefaultChange"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import "./index.scss";
</style>
